﻿using System;
using System.Security.Permissions;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.XPath;
using Com.FastSearch.SharePoint.Interfaces;

namespace Com.FastSearch.SharePoint.WebControls.ESPSearchWebParts.UI
{
    /// <summary>
    /// Shows the did you mean or query rewrites, depending on the query suggest mode choosen.
    /// Available modes are:
    /// - None. Does nothing if no results where found
    /// - Suggest. Suggest a new query if no results have been found or if the spellchecking on the query seems wrong.
    /// - Auto. Automatically rewrite the query (using spellchecking) and resubmit the search if no results where found.
    /// </summary>
    public class ESPDidYouMean : ESPSearchWebPart
    {
        #region Private variables

        /// <summary>
        /// <see cref="IXPathNavigable"/> (XmlDocument) containing the did you mean as xml document which is used for the xslt transormation.
        /// </summary>
        private IXPathNavigable didYouMeanXml = null;

        #endregion

        #region ESPSearchWebPart overrides

        /// <inheritdoc/>
        public override string GetEmbeddedXsl()
        {
            return LoadXslFromAssembly("DidYouMean.xslt");
        }

        /// <inheritdoc/>
        protected override void ConfigureSearch()
        {
            // Nothing to do
        }

        /// <inheritdoc/>
        [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        protected override XPathNavigator GetXPathNavigator(string viewPath)
        {
            if (didYouMeanXml != null)
            {
                return didYouMeanXml.CreateNavigator();
            }
            // Empty result list
            return new XmlDocument().CreateNavigator();
        }

        /// <inheritdoc/>
        public override void SetSearchResult(IESPSearchResult SearchResult)
        {

            if (SearchResult != null)
            {
                didYouMeanXml = SearchResult.GetXmlDidYouMean(Page.Request, ESPSearchGroupID, SearchRequest);
            }
        }
        #endregion
    }
}
